package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-17
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
        /**
         * 课程分类分为三级
         * 思路：
         *      获取根级别分类  一级分类
         *      获取上一级别分类 二级分类
         *      遍历二级分类 获取三级分类
         * @return 课程分类列表vo
         */
        @Override
        public ResponseResult findTreeNodes() {
                // 查询一级分类
                LambdaQueryWrapper<Category> qw1 = new LambdaQueryWrapper<>();
                qw1.eq(Category::getParentid,0);
                Category categoryOne = this.getOne(qw1);
                // 对象转换
                CategoryVo category = BeanHelper.copyProperties(categoryOne, CategoryVo.class);
                // 根据一级分类查询二级分类
                List<CategoryVo> categoryTwo = findByParentId(category.getId());
                category.setCategoryTreeNodes(categoryTwo);
                // 遍历二级分类
                for (CategoryVo twoVo : categoryTwo) {
                        List<CategoryVo> categoryThrees = findByParentId(twoVo.getId());
                        twoVo.setCategoryTreeNodes(categoryThrees);
                }
                return ResponseResult.okResult(category);
        }
        /**
         * 抽取 根据 父级别id查询分类
         * @param parentid 父级别id
         * @return 分类列表
         */
        public List<CategoryVo> findByParentId(String parentid){
                LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
                qw.eq(Category::getParentid,parentid);
                List<Category> categoryList = this.list(qw);
                return BeanHelper.copyWithCollection(categoryList, CategoryVo.class);
        }
}
